/*
 * @Description:
 * @Version: 2.0
 * @Autor: zss
 * @Date: 2025-02-28 09:00:19
 * @LastEditors: zss
 * @LastEditTime: 2025-03-01 13:41:36
 */
import { T_task } from '@/obj/class';
import { ifs } from '@/services';
import { N_flowMonitor, Tsrv } from './config';

class T_cmd {
  // 主组件箱
  private compBox: ifs.I_compBox;

  // 主组件ID
  private compID: string;

  private task: T_task = new T_task(5000);

  // 当前轮询是否开启
  public isOpenTask: boolean = false;

  // 主组件实例
  private self: N_flowMonitor.cFlowMonitor;
  // 主组refs

  // 主组件created里初始化
  public init(
    self: N_flowMonitor.cFlowMonitor,
    compBoxInfo: ifs.I_compBoxInfo
  ) {
    this.self = self;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
  }

  public startTask() {
    this.task.addTask(this.readData);
    this.task.startTask();
    this.isOpenTask = true;
  }

  public stopTask() {
    this.task.delTask(this.readData);
    this.task.stopTask();
    this.isOpenTask = false;
  }

  private readData = () => {
    const codes = [];
    this.self.wasteWaterData.forEach(flow => {
      Object.keys(flow).forEach(key => {
        if (!Tsrv.noValue(flow[key].code)) {
          codes.push(flow[key].code);
        }
      });
    });

    Object.keys(this.self.otherFlowData).forEach(key => {
      codes.push(this.self.otherFlowData[key].code);
    });

    this.readPlcData(codes).then(
      (data: ifs.I_scadaReadResp['data'] | boolean) => {
        if (data) {
          this.self.updateData(data);
        }
      }
    );
  };

  public readPlcData(
    codes: string[]
  ): Promise<ifs.I_scadaReadResp['data'] | boolean> {
    return new Promise((resolve, reject) => {
      Tsrv.standardPostReq<ifs.I_scadaReadResp, any>(
        { ecDetCodes: codes },
        Tsrv.url.scadaRead
      ).then(([readResp, err]) => {
        if (!Tsrv.noValue(err)) {
          this.self.$msg(err);
          this.task.switchIntervalTime(10000); // 读取失败，等待10秒后重试
          reject(false);
        }
        if (!readResp.success) {
          this.self.$msg(readResp.msg);
          this.task.switchIntervalTime(10000); // 读取失败，等待10秒后重试
          reject(false);
        }
        resolve(readResp.data);
      });
    });
  }
}
interface I_cmd extends T_cmd {}
export { I_cmd, T_cmd };
